from itertools import groupby
import copy


class My_Util:

    def __init__(self, context):
        self.context = context

    def sort_import_order(self, imports: list[str]):
        """
        排序导入语句
        """
        basis: list[str] = self.context["code_config"]["java"]["import_order"]
        target = copy.copy(imports)
        target = sorted(target)
        all_grouped_items = [
            (key, list(group))
            for key, group in groupby(
                target, key=lambda item: item.split(" ")[1].split(".")[0]
            )
        ]

        grouped_items = list(filter(lambda item: item[0] in basis, all_grouped_items))
        undeclared_items = list(
            filter(lambda item: item[0] not in basis, all_grouped_items)
        )
        grouped_items.sort(key=lambda item: basis.index(item[0]))
        undeclared_items.sort(key=lambda item: item[0])
        results = list[str]()
        for item in grouped_items:
            results.extend(item[1])
            results.append("")
        for item in undeclared_items:
            results.extend(item[1])
            results.append("")
        if results[-1] == "":
            results = results[:-1]
        return results
